#include "GroupWorker.hh"

GroupWorker::GroupWorker(BlockingQueue* AssignedQueue, Group* AssignedGroup)
: Worker(AssignedQueue)
{
	if (!State)
		return;
	
	State = false;
	
	JoinedGroup = AssignedGroup;
	checkNullFV(JoinedGroup, "JoinedGroup is NULL.");
	
	IdWithinGroup = JoinedGroup->ListOfWorker->join(this);
	if (IdWithinGroup == WorkerChain::InvalidId)
	{
		notifyError(IdWithinGroup, "JoinedGroup->MemberList->join.");
		return;
	}
	
	State = true;
}

GroupWorker::~GroupWorker()
{
	if (State)
	{
		ResultOf Result;
		Result = JoinedGroup->ListOfWorker->secede(IdWithinGroup);
		checkErrorWOR(Result, "Fail JoinedGroup->MemberList->secede.");
	}
}

ResultOf GroupWorker::doWorking()
{
	ResultOf Result;
	do
	{
		if (!checkRetired())
		{
			Result = setLife(1);
			checkErrorWR(Result, "Fail setLife.");
		}
		
		Result = Worker::doWorking();
		checkErrorWR(Result, "Fail Worker::doWorking.");
	}
	while (JoinedGroup->tellMin() >= JoinedGroup->ListOfWorker->tellSize());
	return RETURN_OK;
}

ResultOf GroupWorker::handleTask(Task* AssignedTask)
{
	ResultOf Result;
	Result = JoinedGroup->enter();
	checkErrorWR(Result, "Fail JoinedGroup->enter.");
	
	Result = AssignedTask->perform();
	checkErrorWOR(Result, "Fail AssignedTask->perform.");
	delete AssignedTask;
	
	Result = JoinedGroup->exit();
	checkErrorWR(Result, "Fail JoinedGroup->exit.");
	
	return RETURN_OK;
}

ResultOf GroupWorker::finalizeTask()
{
	ResultOf Result;
	if (JoinedGroup->ListOfWorker->tellSize() > 1)
	{
		Result =  entrustTask();
		checkErrorWR(Result, "Fail entrustTask.");
	}
	else
	{
		Result = Worker::finalizeTask();
		checkErrorWR(Result, "Fail Worker::finalizeTask.");
	}
	
	return RETURN_OK;
}

ResultOf GroupWorker::entrustTask()
{
	ResultOf Result;
	Result = QueueOfTask->release();
	checkErrorWR(Result, "Fail QueueOfTask->release.");
	
	return RETURN_OK;
}

ResultOf GroupWorker::resign()
{
	ResultOf Result;
    Result = Worker::resign();
	checkErrorWR(Result, "Fail Worker::resign.");
	
	delete this;
	return RETURN_OK;
}
